//
//  Player.m
//  TribleWar
//
//  Created by ＣＳＴ ＣＳＴ on 8/11/12.
//  Copyright (c) 2012 ＣＳＴ. All rights reserved.
//

#import "Sprite.h"
#define SPEED 50
@implementation Sprite
@synthesize curCoord;
@synthesize posCoord;
@synthesize pid;
@synthesize image;

-(id)init
{
    if (self = [super init]) {
        self.bounds = CGRectMake(0., 0., 20., 20.);
        self.backgroundColor = [[UIColor clearColor] CGColor];
        self.contents = (id)[[UIImage imageNamed:@"Ball.png"] CGImage];
    }
    return self;
}

- (void)moveAnchorPoint
{    
    [self removeAnimationForKey:@"playermove"];
    CGMutablePathRef movePath = CGPathCreateMutable();
    CALayer *layer = self.presentationLayer;
    curCoord = layer.position;
    CGPathMoveToPoint(movePath, NULL, self.curCoord.x, self.curCoord.y);
    CGPathAddLineToPoint(movePath, NULL, self.posCoord.x, self.posCoord.y);
    
    CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    moveAnimation.path = movePath;
    
    CGFloat distance = [self distanceBetweenPoints:self.curCoord point2:self.posCoord];
    CFTimeInterval durateTime = distance/SPEED;
    moveAnimation.duration = durateTime;
    
    //move with constant speed
    moveAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    
    moveAnimation.delegate = self;
    
    CGPathRelease(movePath);
    [self addAnimation:moveAnimation forKey:@"playermove"];
    
}
- (void)animationDidStart:(CAAnimation *)theAnimation {
    [CATransaction begin];
    {
        [CATransaction setDisableActions:YES];
        self.position = self.posCoord;
    }
    [CATransaction commit];
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)finished {
    [CATransaction begin];
    {
        [CATransaction setDisableActions:YES]; 
        if(finished) {
            self.curCoord = self.posCoord;
        }
    }
    [CATransaction commit];
}

- (CGFloat)distanceBetweenPoints:(CGPoint) point1 point2:(CGPoint)point2
{
    CGFloat dx = point2.x - point1.x;
    CGFloat dy = point2.y - point1.y;
    return sqrtf(dx*dx+dy*dy);
}

@end
